package main

import (
	"encoding/json"
	"fmt"
	"gitee.com/hlwqds/rabitmqTest/config"
	"gitee.com/hlwqds/rabitmqTest/log"
	"gitee.com/hlwqds/rabitmqTest/rabbitmqInAction/rpcServer/rpcConfig"
	"gitee.com/hlwqds/rabitmqTest/rabbitmqInAction/rpcServer/rpcMessage"
	"github.com/streadway/amqp"
	"time"
)

func main(){
	conn, err := amqp.Dial(config.GenURLFromConfig())
	log.FailOnError(err, "amqp.Dial error")
	defer conn.Close()
	ch, err := conn.Channel()
	log.FailOnError(err, "conn.Channel error")
	defer ch.Close()
	resultQueue, err := ch.QueueDeclare(
		"",
		false,
		true,
		true,
		false,
		nil)

	resultCh, err := ch.Consume(
		resultQueue.Name,
		resultQueue.Name,
		true,
		false,
		false,
		false,
		nil,
		)

	messageStruct := rpcMessage.Message{
		ClientName: "client1",
		Time: time.Now().Unix(),
	}
	messageJson, err := json.Marshal(&messageStruct)

	ch.Publish(
		rpcConfig.RpcExchange,
		"ping",
		false,
		false,
		amqp.Publishing{
			ContentType: "application/json",
			Body: messageJson,
			ReplyTo: resultQueue.Name,
		})
	var resultData amqp.Delivery

	select{
	case resultData = <-resultCh:
		fmt.Printf("RPC Reply --- %s\n", resultData.Body)
	case <-time.NewTimer(time.Second * 3).C:
		fmt.Println("Timeout!")
	}

	ch.Cancel(resultQueue.Name, false)
}